package com.amm.gwt.gwtgaeuploader.server;

import com.amm.gwt.gwtgaeuploader.client.service.GAEUploadRPC;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class GWTGAEUploadRPCImpl extends RemoteServiceServlet implements GAEUploadRPC {

    private static String myAppengineHost;

    public String getUploadUrl(String myAppengineHost) {
        GWTGAEUploadRPCImpl.myAppengineHost = myAppengineHost;

        String inputLine = null;

        try {
            URL url = new URL(myAppengineHost + "/uploadUrl");
            URLConnection conn = url.openConnection();
            DataInputStream dis = new DataInputStream(conn.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            while (br.ready())
                inputLine = br.readLine();

            dis.close();
        } catch (MalformedURLException me) {
            me.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return inputLine;
    }

    public String getServingUrl(String myAppengineHost, String uploadUrl) {
        GWTGAEUploadRPCImpl.myAppengineHost = myAppengineHost;

        String inputLine = null;

        try {
            URL url = new URL(myAppengineHost + "/servingUrl?uploadUrl=" + uploadUrl);
            URLConnection conn = url.openConnection();
            DataInputStream dis = new DataInputStream(conn.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            while (br.ready())
                inputLine = br.readLine();

            dis.close();
        } catch (MalformedURLException me) {
            me.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return inputLine;
    }
}